from django.shortcuts import render, redirect
from webadmin.models import HostGroup, Module, Host, Argument
from webadmin.adhoc2 import adhoc

def index(request):
    return render(request, 'mainpage.html')

def add_hosts(request):
    if request.method == 'POST':
        groupname = request.POST.get('group').strip()  # 去除额外的空白字符
        hostname = request.POST.get('host').strip()
        ip = request.POST.get('ip').strip()
        if groupname:   # 如果提交的组名非空
            g = HostGroup.objects.get_or_create(groupname=groupname)[0]
            if hostname and ip:  # 如果提交的主机名和ip都非空
                g.host_set.get_or_create(hostname=hostname, ip=ip)

    groups = HostGroup.objects.all()  # 取出全部组
    return render(request, 'add_hosts.html', {'groups': groups})

def add_modules(request):
    if request.method == 'POST':
        modulename = request.POST.get('module').strip()
        args = request.POST.get('param').strip()
        if modulename:
            m = Module.objects.get_or_create(modulename=modulename)[0]
            if args:
                m.argument_set.get_or_create(arg_text=args)

    modules = Module.objects.all()
    return render(request, 'add_modules.html', {'modules': modules})

def tasks(request):
    if request.method == 'POST':
        ip = request.POST.get('host')
        group = request.POST.get('group')
        module = request.POST.get('module')
        args = request.POST.get('param')
        # 确定在主机上，还是在组上执行任务，在谁上面执行任务，就把它赋值给目标dest
        if ip:   # 如果ip非空
            dest = ip
        elif group:
            dest = group
        else:
            dest = None

        if dest:  # None为假，如果dest的值是ip或group，则为真。为真就开始在目标执行任务
            adhoc(['ansible_cfg/dhosts.py'], dest, module, args)


    groups = HostGroup.objects.all()
    hosts = Host.objects.all()
    modules = Module.objects.all()
    data = {'groups': groups, 'hosts': hosts, 'modules': modules}
    return render(request, 'tasks.html', data)

def del_arg(request, arg_id):
    arg = Argument.objects.get(id=arg_id)
    arg.delete()
    return redirect('add_modules')
